package br.com.tecnoria.util
{
	import flash.events.Event;
	
	import mx.collections.ArrayCollection;
	import mx.controls.ComboBox;


	/**
	 *  Dispatched when the default index is chaged
	 * 
	 */
	[Event(name="defaultIndexChanged", type="flash.events.Event")]

	/**
	 *  Dispatched when the property value is chaged
	 * 
	 */
	[Event(name="propertyValueChanged", type="flash.events.Event")]

	/**
	 * @author mariojunior
	 */
	public class ComboBoxSelected extends ComboBox
	{

		private var _defaultIndex:int=-1;
		private var _property:String;
		private var _selectedValue:Object;


		[Bindable("defaultIndexChanged")]
		public function get defaultIndex():int
		{
			return this._defaultIndex;
		}

		public function set defaultIndex(index:int):void
		{
			this._defaultIndex=index;
			dispatchEvent(new Event("defaultIndexChanged"));
			invalidateProperties();
		}

		[Bindable("propertyValueChanged")]
		public function get property():String
		{
			return this._property;
		}

		public function set property(value:String):void
		{
			this._property=value;
			dispatchEvent(new Event("propertyValueChanged"));
			invalidateProperties();
		}

		[Bindable("selectedValueChanged")]
		public function get selectedValue():Object
		{
			return this._selectedValue;
		}

		public function set selectedValue(value:Object):void
		{
			this._selectedValue=value;
			dispatchEvent(new Event("selectedValueChanged"));
			invalidateProperties();
		}

		/**
		 *
		 *
		 */
		override protected function commitProperties():void
		{
			super.commitProperties();
			var i:int;
			var dpLength:int
			var propertyToCompare:String=(_property != null) ? _property : labelField;

			if (this.dataProvider != null)
			{
				if (_selectedValue != null)
				{
					dpLength=(this.dataProvider as ArrayCollection).length;

					try
					{
						for (i; i <= dpLength; i++)
						{
							if (_selectedValue == this.dataProvider[i][propertyToCompare])
							{
								this.selectedIndex=i;
								this.selectedItem=this.dataProvider[i];
								break;
							}
						}
					}
					catch (e:Error)
					{
						this.selectedIndex=-1;
						this.selectedItem=null;
						trace("Error: " + e.message);
					}
					if (this.selectedIndex == -1)
					{
						this.selectedIndex=this._defaultIndex;
					}
				}
				else
				{
					this.selectedIndex=this._defaultIndex;
					trace("selectedValue null.");
				}
			}
		}
	}
}